<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { fetchCourseInformationApi, modifyCourseInformationApi } from '@/api/Teacher/courseApi';

// 定义 props
const props = defineProps<{
  visible: boolean;
  onClose: () => void;
  courseId: string;
  fetchCourses: (search: string) => Promise<void>;
}>();

// URL 转为 File 对象的方法
const urlToFile = async (url: string, filename: string, mimeType: string): Promise<File> => {
  const response = await fetch(url);
  const blob = await response.blob();
  return new File([blob], filename, { type: mimeType });
};

// 响应式数据
const loading = ref(false);
const folderId = ref('');
const teacherId = ref('');
const courseImage = ref<any[]>([]);
const courseName = ref('');
const courseTags = ref('');
const courseDescription = ref('')
const teachers = ref<any[]>([{ name: '', institution: '', position: '', title: '', imageFile: null, imagePreview: null }]);
const form = ref<any>(null);

// 获取课程信息函数
const fetchCourseInformation = async () => {
  loading.value = true;
  try {
    const response = await fetchCourseInformationApi(props.courseId)
    const course = response.data;
    folderId.value = course.folderId;
    teacherId.value = course.teacherId;
    courseName.value = course.courseName;
    courseTags.value = course.courseTag;
    courseDescription.value = course.courseDescription

    // 将课程图片 URL 转为 File 对象
    if (course.courseImage) {
      const courseImageFile = await urlToFile(course.courseImage, 'course_image.png', 'image/png');
      courseImage.value = [{ originFileObj: courseImageFile }];
    }

    // 将教师图片 URL 转为 File 对象
    const updatedTeachers = await Promise.all(
      course.teacher.map(async (teacher: any, index: number) => {
        let teacherImageFile = null;
        if (teacher.teacherImage)
          teacherImageFile = await urlToFile(teacher.teacherImage, `teacher_image_${index}.png`, 'image/png');

        return {
          name: teacher.teacherName,
          institution: teacher.teacherSchool,
          position: teacher.teacherJob,
          title: teacher.teacherTitle,
          imageFile: teacherImageFile,
          imagePreview: teacher.teacherImage, // 原始 URL 作为预览图像
        };
      }),
    );

    teachers.value = updatedTeachers;
  }
  catch (error) {
    message.error('获取课程信息失败');
  }
  finally {
    loading.value = false;
  }
};
watch(() => props.visible, (newVal) => {
  if (newVal)
    fetchCourseInformation(); // 如果模态框显示，获取章节数据
});
// 处理课程图片上传
const handleCourseImageChange = ({ fileList }: any) => {
  courseImage.value = fileList;
};

// 处理教师图片上传
const handleTeacherImageChange = (index: number, { fileList }: any) => {
  const file = fileList[0]; // 获取上传的第一个文件
  if (file) {
    const objectURL = URL.createObjectURL(file.originFileObj); // 创建对象URL
    teachers.value[index].imageFile = file.originFileObj; // 保存文件对象
    teachers.value[index].imagePreview = objectURL; // 将预览 URL 存储为响应式属性
  }
  else {
    // 如果 fileList 为空，则清除图像文件和预览
    teachers.value[index].imageFile = null;
    teachers.value[index].imagePreview = null;
  }
};

// 添加教师
const handleAddTeacher = () => {
  teachers.value.push({ name: '', institution: '', position: '', title: '', imageFile: null, imagePreview: null });
};

// 删除教师
const handleRemoveTeacher = (index: number) => {
  teachers.value.splice(index, 1);
};

// 提交表单
const handleOk = async () => {
  try {
    loading.value = true;
    const courseFormData = new FormData();

    // 将课程图片上传
    if (courseImage.value.length > 0 && courseImage.value[0].originFileObj)
      courseFormData.append('files', courseImage.value[0].originFileObj);

    // 构造教师列表
    const filteredTeachers = teachers.value.filter(
      teacher => teacher.name && teacher.institution && teacher.position && teacher.title,
    );

    const teacherList = filteredTeachers.map((teacher, index) => {
      if (teacher.imageFile)
        courseFormData.append('files', teacher.imageFile);

      return {
        // id: index + 1,
        teacherName: teacher.name,
        teacherSchool: teacher.institution,
        teacherJob: teacher.position,
        teacherTitle: teacher.title,
        teacherImage: '',
      };
    });

    const payload = {
      // courseId: useCourseStore().courseid,
      // teacherId: teacherId.value,
      // folderId: folderId.value,
      courseName: courseName.value,
      courseTag: courseTags.value,
      // courseImage: '',
      courseDescription: courseDescription.value,
      teacher: teacherList,

    };
    courseFormData.append('courseId', props.courseId || '');
    courseFormData.append('course', JSON.stringify(payload));

    // 提交到后端
    await modifyCourseInformationApi(courseFormData);
    message.success('课程修改成功');
    props.fetchCourses('');
    props.onClose();
  }
  catch (error) {
    message.error('请求失败');
  }
  finally {
    loading.value = false;
    form.value.resetFields();
    courseImage.value = [];
    teachers.value = [{ name: '', institution: '', position: '', title: '', imageFile: null, imagePreview: null }];
  }
}

// 页面加载时获取数据
onMounted(() => {
  if (props.visible)
    fetchCourseInformation();
});
</script>

<template>
  <a-modal
    :open="props.visible"
    title="编辑课程"
    ok-text="确定"
    cancel-text="取消"
    :width="600"
    @cancel="props.onClose"
    @ok="handleOk"
  >
    <a-spin :spinning="loading">
      <a-form ref="form" layout="vertical">
        <div style="display: flex;">
          <div style="margin-top: 20px;">
            <a-upload
              accept="image/*"
              list-type="picture-card"
              :file-list="courseImage"
              @change="handleCourseImageChange"
            >
              <template v-if="courseImage.length < 1">
                <div style="width: 100px; height: 100px; background-color: #f0f0f0;">
                  <PlusOutlined style="margin-top: 30px;" />
                  <div>上传图片</div>
                </div>
              </template>
            </a-upload>
          </div>
          <div style="flex: 1; margin-left: 20px;">
            <a-form-item label="课程名称" name="courseName" rules="[ { required: true, message: '请输入课程名称' } ]">
              <a-input v-model:value="courseName" placeholder="请输入课程名称" />
            </a-form-item>
            <a-form-item label="课程标签" name="tags" rules="[ { required: true, message: '请输入课程标签' } ]">
              <a-input v-model:value="courseTags" placeholder="请输入课程标签" />
            </a-form-item>
          </div>
        </div>

        <div v-for="(teacher, index) in teachers" :key="index" style="margin-bottom: 10px;">
          <h3>授课教师</h3>
          <div style="display: flex; justify-content: space-between;">
            <div style="margin-top: 20px;">
              <a-upload
                accept="image/*"
                list-type="picture-card"
                :show-upload-list="false"
                :max-count="1"
                @change="(info:any) => handleTeacherImageChange(index, info)"
              >
                <template v-if="teacher.imagePreview">
                  <img
                    :src="teacher.imagePreview"
                    alt="教师照片"
                    style="width: 100px; height: 100px;"
                  >
                </template>
                <template v-else>
                  <div style="width: 100px; height: 100px; background-color: #f0f0f0;">
                    <PlusOutlined style="margin-top: 30px;" />
                    <div>上传图片</div>
                  </div>
                </template>
              </a-upload>
            </div>
            <div style="flex: 1; margin-left: 20px;">
              <div style="display: flex;">
                <a-form-item
                  label="姓名"
                  style="flex: 1; margin-right: 10px;"
                >
                  <a-input
                    v-model:value="teacher.name"
                    placeholder="请输入教师姓名"
                  />
                </a-form-item>
                <a-form-item
                  label="学校或机构"
                  style="flex: 1; margin-right: 10px;"
                >
                  <a-input
                    v-model:value="teacher.institution"
                    placeholder="请输入学校或机构"
                  />
                </a-form-item>
              </div>
              <div style="display: flex;">
                <a-form-item
                  label="职务"
                  style="flex: 1; margin-right: 10px;"
                >
                  <a-input
                    v-model:value="teacher.position"
                    placeholder="请输入职务"
                  />
                </a-form-item>
                <a-form-item
                  label="职称"
                  style="flex: 1; margin-right: 10px;"
                >
                  <a-input
                    v-model:value="teacher.title"
                    placeholder="请输入职称"
                  />
                </a-form-item>
              </div>
              <a-button
                type="link"
                style="color: red;"
                @click="handleRemoveTeacher(index)"
              >
                删除
              </a-button>
            </div>
          </div>
        </div>

        <a-button type="dashed" style="width: 100%; margin-bottom: 20px;" @click="handleAddTeacher">
          <PlusOutlined /> 添加教师
        </a-button>

        <a-form-item label="课程简介" name="description">
          <a-textarea v-model:value="courseDescription" placeholder="请输入课程简介" auto-size />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>
